﻿Public Class Threading
    Private Shared mMainGuiForm As System.Windows.Forms.Form
    Public Shared Property MainGuiForm() As System.Windows.Forms.Form
        Get
            Return mMainGuiForm
        End Get
        Set(ByVal value As System.Windows.Forms.Form)
            mMainGuiForm = value
        End Set
    End Property

    Public Shared Function EventInvokeRequired() As Boolean
        If mMainGuiForm Is Nothing Then
            Return False
        Else
            Return mMainGuiForm.InvokeRequired
        End If
    End Function

    Public Delegate Sub InvokeDelegate()
    Public Shared Sub Invoke(ByVal del As InvokeDelegate)
        If EventInvokeRequired() Then
            Try
                mMainGuiForm.Invoke(del)
            Catch ex As ObjectDisposedException
            End Try
        Else
            del.Invoke()
        End If
    End Sub
    Public Delegate Sub InvokeOneArgDelegate(Of T)(ByVal arg As T)
    Public Shared Sub Invoke(Of T)(ByVal del As InvokeOneArgDelegate(Of T), ByVal arg As T)
        If EventInvokeRequired() Then
            Try
                mMainGuiForm.Invoke(del, arg)
            Catch ex As ObjectDisposedException
            End Try
        Else
            del.Invoke(arg)
        End If
    End Sub
    Public Delegate Sub InvokeTwoArgDelegate(Of T1, T2)(ByVal arg1 As T1, ByVal arg2 As T2)
    Public Shared Sub Invoke(Of T1, T2)(ByVal del As InvokeTwoArgDelegate(Of T1, T2), ByVal arg1 As T1, ByVal arg2 As T2)
        If EventInvokeRequired() Then
            Try
                mMainGuiForm.Invoke(del, arg1, arg2)
            Catch ex As ObjectDisposedException
            End Try
        Else
            del.Invoke(arg1, arg2)
        End If
    End Sub
    Public Delegate Sub InvokeThreeArgDelegate(Of T1, T2, T3)(ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3)
    Public Shared Sub Invoke(Of T1, T2, T3)(ByVal del As InvokeThreeArgDelegate(Of T1, T2, T3), ByVal arg1 As T1, ByVal arg2 As T2, ByVal arg3 As T3)
        If EventInvokeRequired() Then
            Try
                mMainGuiForm.Invoke(del, arg1, arg2, arg3)
            Catch ex As ObjectDisposedException
            End Try
        Else
            del.Invoke(arg1, arg2, arg3)
        End If
    End Sub

End Class
